import { User } from "server/models/User";
import {
  successResponse,
  errorResponse,
  validationErrorResponse,
} from "server/utils/response";

export default defineEventHandler(async (event) => {
  try {
    const { id } = getRouterParams(event);
    const body = await readBody(event);
    const { oldPassword, newPassword, confirmPassword } = body;

    if (!id) {
      return validationErrorResponse("用户ID不能为空");
    }

    // 验证必填字段
    if (!oldPassword) {
      return validationErrorResponse("原密码不能为空");
    }

    if (!newPassword) {
      return validationErrorResponse("新密码不能为空");
    }

    if (!confirmPassword) {
      return validationErrorResponse("确认密码不能为空");
    }

    // 验证新密码长度
    if (newPassword.length < 6) {
      return validationErrorResponse("新密码长度不能少于6个字符");
    }

    // 验证新密码和确认密码是否一致
    if (newPassword !== confirmPassword) {
      return validationErrorResponse("新密码和确认密码不一致");
    }

    // 验证新密码和原密码是否相同
    if (oldPassword === newPassword) {
      return validationErrorResponse("新密码不能与原密码相同");
    }

    try {
      const userId = parseInt(id);
      const success = await User.changePassword(userId, oldPassword, newPassword);

      if (!success) {
        return errorResponse("密码修改失败", "用户不存在");
      }

      return successResponse(null, "密码修改成功");
    } catch (dbError: any) {
      console.error("数据库操作失败:", dbError);
      if (dbError.message.includes('用户不存在')) {
        return errorResponse("用户不存在", "用户未找到");
      }
      if (dbError.message.includes('原密码错误')) {
        return validationErrorResponse("原密码错误");
      }
      return errorResponse("密码修改失败", "数据库错误");
    }
  } catch (error) {
    console.error("密码修改失败:", error);
    return errorResponse(
      "密码修改失败",
      error instanceof Error ? error.message : "未知错误"
    );
  }
});